<template>
  <div class="sales-dashboard">
    <h1>销售数据仪表板</h1>

     <div class="stats-row">
      <div class="stat-card">
        <div class="stat-value">¥{{ totalSalesAmount }}</div>
        <div class="stat-label">总销售额</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ totalSalesCount }}</div>
        <div class="stat-label">订单数量</div>
      </div>
    </div>
    <!-- 第一行：销售趋势图和产品销售柱状图 -->
    <div class="chart-row">
      <div class="chart-card">
        <div ref="trendChartRef" class="chart-container"></div>
      </div>
      <div class="chart-card">
        <div ref="productChartRef" class="chart-container"></div>
      </div>
    </div>

    <!-- 第二行：销售渠道占比 -->
    <!-- <div class="chart-row">
      <div class="chart-card">
        <div ref="channelChartRef" class="chart-container"></div>
      </div>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// DOM refs
const trendChartRef = ref(null);
const productChartRef = ref(null);
// const channelChartRef = ref(null);

// ECharts 实例
let trendChart = null;
let productChart = null;
// let channelChart = null;

// 数据
const monthTrendList = ref([]);
const salesCountList = ref([]);
const totalSalesAmount = ref(0);
const totalSalesCount = ref(0);

// 获取销售数据
const selectChart = async () => { 
    try {
        const response = await axios.get('/api/sales/salesSlipChart');
        if(response.data.code == 5200){
            monthTrendList.value = response.data.monthTrendList;
            salesCountList.value = response.data.salesCountList;
            totalSalesAmount.value = response.data.addSalesPrice;
            totalSalesCount.value = response.data.addSalesCount;
            // 数据更新后重新渲染图表
            updateCharts();
        }else{
            ElMessage.error(response.data.msg);
        }
    } catch (error) {
        ElMessage.error('获取销售数据失败');
        console.error(error);
    }
};

// 更新图表数据
const updateCharts = () => {
    if (trendChart) {
        trendChart.setOption(getTrendChartOption(), true); // true表示不合并选项
    }
    if (productChart) {
        productChart.setOption(getProductChartOption(), true);
    }
};

// 初始化所有图表
const initAllCharts = () => {
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value);
    trendChart.setOption(getTrendChartOption());
  }

  if (productChartRef.value) {
    productChart = echarts.init(productChartRef.value);
    productChart.setOption(getProductChartOption());
  }

//   if (channelChartRef.value) {
//     channelChart = echarts.init(channelChartRef.value);
//     channelChart.setOption(getChannelChartOption());
//   }

  window.addEventListener('resize', handleResize);
};

// 响应窗口大小变化
const handleResize = () => {
  trendChart?.resize();
  productChart?.resize();
//   channelChart?.resize();
};

// 销毁图表实例
const disposeCharts = () => {
  trendChart?.dispose();
  productChart?.dispose();
//   channelChart?.dispose();
  window.removeEventListener('resize', handleResize);
};

// 图表配置项 - 使用真实数据
const getTrendChartOption = () => {
  // 处理月份趋势数据
  const months = monthTrendList.value.map(item => `${item.month}月`);
  const salesData = monthTrendList.value.map(item => parseFloat(item.totalSales.toFixed(2)));
  
  return {
    title: { text: '月度销售趋势', left: 'center' },
    tooltip: { 
      trigger: 'axis',
      formatter: (params) => {
        const param = params[0];
        return `${param.name}<br/>${param.marker} 销售额: ${param.value} 元`;
      }
    },
    xAxis: {
      type: 'category',
      data: months.length > 0 ? months : ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      axisLabel: { formatter: '{value} 元' }
    },
    series: [{
      name: '销售额',
      data: salesData.length > 0 ? salesData : [120, 132, 101, 134, 90, 230],
      type: 'line',
      smooth: true,
      itemStyle: { color: '#409EFF' },
      areaStyle: { opacity: 0.3 }
    }]
  };
};

const getProductChartOption = () => {
  // 处理产品销售数据
  const productNames = salesCountList.value.map(item => item.productName);
  const quantities = salesCountList.value.map(item => item.totalQuantity);
  
  return {
    title: { text: '产品销售前五', left: 'center' },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const param = params[0];
        return `${param.name}<br/>${param.marker} 销量: ${param.value} 件`;
      }
    },
    xAxis: {
      type: 'category',
      data: productNames.length > 0 ? productNames : ['产品A', '产品B', '产品C', '产品D', '产品E']
    },
    yAxis: {
      type: 'value',
      axisLabel: { formatter: '{value} 件' }
    },
    series: [{
      name: '销量',
      data: quantities.length > 0 ? quantities : [120, 200, 150, 80, 70],
      type: 'bar',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      }
    }]
  };
};



// 监听数据变化并更新图表
watch([monthTrendList, salesCountList], () => {
  updateCharts();
});

// 生命周期钩子
onMounted(() => {
    selectChart();
    initAllCharts();
});

onBeforeUnmount(() => {
  disposeCharts();
});
</script>

<style scoped>
.sales-dashboard {
  padding: 20px;
}

.sales-dashboard h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.chart-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 20px;
}

.chart-card {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-container {
  width: 100%;
  height: 350px;
}

@media (max-width: 768px) {
  .chart-row {
    flex-direction: column;
  }

  .chart-card {
    margin-bottom: 20px;
  }
}

.stats-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .stats-row {
    flex-direction: column;
  }
  
  .stat-card {
    margin-bottom: 10px;
  }
}
</style>